var pd = require('pd');

module.exports = {
    every: function every(timeout, now /* = true */) {
        this.cancel();
        this._active = true;
        this._timeout = timeout;
    
        if (now || now === undefined) {
            this._invoke();
        } else {
            this.next();
        }
    },
    next: function next() {
        if (this._active) {
            this._id = setTimeout(invoke.bind(this), this._timeout);
        }
    },
    stop: function () {
        this._active = false;
        this.cancel();
    },
    cancel: function () {
        clearTimeout(this._id);
    },
    constructor: function constructor(invoke) {
        pd.bindAll(this);
    
        if (typeof invoke !== 'function') {
            throw new Error("invoke is not a function");
        }
        
        this._active = false;
        this._invoke = invoke;
    }
};

function invoke() {
    this._invoke();
}